package org.example.device.protocol;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.util.HashMap;
import java.util.Map;

/**
 * HTTP设备协议实现
 * 用于HTTP REST API的智能设备通信
 */
@Component
public class HttpDeviceProtocol implements DeviceProtocol {
    
    private static final String PROTOCOL_TYPE = "HTTP";
    
    @Autowired
    @Qualifier("deviceControlRestTemplate")
    private RestTemplate restTemplate;
    
    private String baseUrl;
    
    @Override
    public ProtocolResult sendCommand(Long deviceId, String command, Map<String, Object> parameters) {
        try {
            String url = baseUrl + "/devices/" + deviceId + "/control";
            
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("command", command);
            requestBody.put("parameters", parameters);
            requestBody.put("timestamp", System.currentTimeMillis());
            
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
            
            if (response.getStatusCode().is2xxSuccessful()) {
                return ProtocolResult.success("HTTP命令发送成功", response.getBody());
            } else {
                return ProtocolResult.failure("HTTP命令发送失败: " + response.getStatusCode());
            }
        } catch (Exception e) {
            return ProtocolResult.failure("HTTP命令发送异常: " + e.getMessage(), "HTTP_SEND_ERROR");
        }
    }
    
    @Override
    public ProtocolResult getDeviceStatus(Long deviceId) {
        try {
            String url = baseUrl + "/devices/" + deviceId + "/status";
            
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            
            if (response.getStatusCode().is2xxSuccessful()) {
                return ProtocolResult.success("设备状态获取成功", response.getBody());
            } else {
                return ProtocolResult.failure("设备状态获取失败: " + response.getStatusCode());
            }
        } catch (Exception e) {
            return ProtocolResult.failure("获取设备状态异常: " + e.getMessage(), "HTTP_STATUS_ERROR");
        }
    }
    
    @Override
    public ProtocolResult checkConnection(Long deviceId) {
        try {
            String url = baseUrl + "/devices/" + deviceId + "/ping";
            
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            
            if (response.getStatusCode().is2xxSuccessful()) {
                return ProtocolResult.success("设备连接正常");
            } else {
                return ProtocolResult.failure("设备连接异常: " + response.getStatusCode());
            }
        } catch (Exception e) {
            return ProtocolResult.failure("设备连接检查异常: " + e.getMessage(), "HTTP_CONNECTION_ERROR");
        }
    }
    
    @Override
    public String getProtocolType() {
        return PROTOCOL_TYPE;
    }
    
    @Override
    public boolean initialize(Map<String, Object> config) {
        try {
            this.baseUrl = (String) config.get("baseUrl");
            if (baseUrl == null || baseUrl.isEmpty()) {
                throw new IllegalArgumentException("HTTP协议需要配置baseUrl");
            }
            
            System.out.println("初始化HTTP协议连接: " + baseUrl);
            return true;
        } catch (Exception e) {
            System.err.println("HTTP协议初始化失败: " + e.getMessage());
            return false;
        }
    }
    
    @Override
    public void shutdown() {
        try {
            System.out.println("关闭HTTP协议连接");
            this.baseUrl = null;
        } catch (Exception e) {
            System.err.println("HTTP协议关闭失败: " + e.getMessage());
        }
    }
}
